package com.yoga.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yoga.entity.YogaUser;
import com.yoga.service.PhotoUploadService;
import com.yoga.utils.ResultVO;

import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@Configuration
@RestController
public class PhotoUpload{
    @Autowired
    private PhotoUploadService photoUploadService;
    @Value("${file.upload-dir}")
    private String uploadDir;
    @RequestMapping("photo")
    public ResultVO photo(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws ServletException, IOException {
        String fileName = file.getOriginalFilename();
        Integer uid = Integer.parseInt(request.getParameter("uid"));
        try {
            UUID uuid = UUID.randomUUID();
            File file1 = new File(uploadDir, uuid + fileName);
            file.transferTo(file1);
        String substring = file1.getPath().substring(file1.getPath().lastIndexOf("\\"));
            photoUploadService.addPhoto(uid, "http://localhost:8080/photo"+substring);
            YogaUser one = photoUploadService.findOne(uid);
            return ResultVO.success("文件上传成功！", one);
        } catch(IOException e) {
            e.printStackTrace();

        }
            return ResultVO.fail("失败");

    }

}
